package de.dopichaj.labrador.search.merge.pattern;

import java.util.ArrayList;
import java.util.List;
import java.util.SortedSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;

import de.dopichaj.labrador.search.hit.Hit;


/**
 * A generic pattern that takes a pattern description in string format
 * (see {@link #GenericPattern} for details).
 */
public final class GenericPattern extends AbstractPattern {

    private static final Logger log = Logger.getLogger(GenericPattern.class);
    private final Pattern[] patterns;
    private final String[] boostStrings;
    private boolean didMatch = false;
    
    /**
     * Construct a generic pattern.
     * Patterns consist of parts, and each part has three components:
     * <ul>
     * <li>The length part (S, M, L, D for short, medium length, long, don't care)</li>
     * <li>The repetition part (0 times, 1 time, + one or more, * zero or more)</li>
     * <li>The rule part (d, k, h, z for double, keep, halve, set to zero)</li>
     * </ul>
     * @param patternString
     */
    public GenericPattern(final String ... patternStrings) {
        
        patterns = new Pattern[patternStrings.length];
        boostStrings = new String[patternStrings.length];
        for (int i = 0; i < patternStrings.length; i++) {
            final String patternString = patternStrings[i];
            if (!Pattern.matches("^([ABCDEFGH][01+*][dkhz])*$", patternString)) {
                throw new IllegalArgumentException("Invalid pattern string " +
                    i + ": " +
                    patternString);
            }
            
            // translate the pattern
            final String prunedPatternString = patternString.replaceAll(".0.", "");
            boostStrings[i] = prunedPatternString.replaceAll("..(.)", "$1");
            final String regexString = "^" + prunedPatternString.
                replaceAll("(..).", "$1").  // remove output value
                replaceAll(".0", "").       // remove inactive genes
                replaceAll("(..)", "($1)"). // create groups
                replaceAll("1", "").        // replace count of 1
                replaceAll("A", "S").
                replaceAll("B", "M").
                replaceAll("C", "L").
                replaceAll("D", "[SM]").
                replaceAll("E", "[SL]").
                replaceAll("F", "[ML]").
                replaceAll("G", "[SML]").
                replaceAll("H", "[SML]") + "$";
            patterns[i] = Pattern.compile(regexString);
            
            log.debug("Input pattern " + i + ": " + patternString +
                "; regex: " + regexString);
        }
    }

    @Override
    public void applyTo(final Hit parent, final SortedSet<Hit> children) {
        
        // build the hit string
        final StringBuilder hitString = new StringBuilder();
        hitString.append(hitToChar(parent));
        for (final Hit child : children) {
            hitString.append(hitToChar(child));
        }
        
        // for each pattern
        for (int i = 0; i < patterns.length; i++) {
            
            // if the pattern matches
            final Matcher matcher = patterns[i].matcher(hitString);
            if (matcher.matches()) {
                
                didMatch  = true;
                
                // update the scores
                final List<Hit> allHits = new ArrayList<Hit>();
                allHits.add(parent);
                allHits.addAll(children);
                for (int g = 1; g <= matcher.groupCount(); g++) {
    
                    final double boost = getBoost(boostStrings[i].charAt(g - 1));
                    
                    for (int hitPos = matcher.start(g);
                        hitPos < matcher.end(g); hitPos++) {
                        boostScore(allHits.get(hitPos), boost, 1.0);
                    }
                }
            }
        }
    }

    /**
     * Get the boost for the given character.
     */
    private double getBoost(final char charAt) {
        final double boost;
        switch (charAt) {
        case 'd':
            boost = 2.0;
            break;
        case 'k':
            boost = 1.0;
            break;
        case 'h':
            boost = 0.5;
            break;
        case 'z':
            boost = 0.0;
            break;
        default:
            boost = 99;
            assert false;
        }
        return boost;
    }

    /**
     * Convert the hit to a character representing its length.
     */
    private char hitToChar(final Hit hit) {
        final int length = hit.getContentLength();
        
        if (length <= 10) {
            return 'S';
        } else if (length <= 100) {
            return 'M';
        } else {
            return 'L';
        }
    }
    
    public boolean didMatch() {
        return didMatch;
    }
}
/*
Copyright (c) 2005-2007 Philipp Dopichaj

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/